package com.news.dao;

import com.news.model.ArticleEntity;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lingzhiyuan.
 * Date : 15/10/9.
 * Time : 下午9:20.
 * Description:
 */

@Repository
public class ArticleDao extends BaseDao{


    public Map findArticleByColumnId(long column_id, int page_size, int page_num) {

        Map result = new HashMap<>();
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(ArticleEntity.class);
        criteria.add(Restrictions.eq("column_id",column_id));
        criteria.addOrder(Order.desc("datetime"));
        result.put("articles",criteria.list());

        return result;
    }

    public List findArticleByColumnId(long column_id) {

        Map result = new HashMap<>();
        Session session = sessionFactory.getCurrentSession();
        Criteria criteria = session.createCriteria(ArticleEntity.class);
        criteria.add(Restrictions.eq("column_id",column_id));
        criteria.addOrder(Order.desc("datetime"));
        return criteria.list();
    }

    public List findAllArticlesByQueryKey(String queryKey) {

        Session session = sessionFactory.getCurrentSession();
        Query query;
        if (queryKey.equals("")){
            query = session.createQuery("from ArticleEntity");
        }else {
            query = session.createQuery("from ArticleEntity where title like :ti");
            query.setParameter("ti","%"+queryKey+"%");
        }
        return query.list();
    }
}
